<template>
    <div class="grade-model-config">
        <IndicatorInfo :dataDict="dataDict" :gradeModelSelectDict="gradeModelSelectDict" :modalData="modalData"/>
        <div class="table">
            <div class="table-btn">
                <Button type="primary" @click="add">新增</Button>
                <Button type="primary" @click="del">删除</Button>
            </div>
            <Table
                highlight-row
                ref="currentRowTable"
                :columns="tableHead"
                :data="tableData"
                @on-current-change="onCurrentChange"
                :loading="loading"
                border
            >
                <template slot-scope="{ row, index }" slot="elementValueRange">
                    <span>{{ getRange(row) }}</span>
                </template>
                <template slot-scope="{ row, index }" slot="elementValue">
                    <span>{{ getValue(row.elementValue, gradeModelSelectDict) }}</span>
                </template>
            </Table>
        </div>
        <GradeSelect :formData="formData" :modalData="modalData" :dataDict="gradeModelSelectDict"/>
        <div>
            <div class="common_br">
                <h2 class="common_channel_title">指标要素得分</h2>
                <div class="common_content">
                    <Row>
                        <Col span="6">
                            <div class="grade-model-tree">
                                <Tree :data="treeData" @on-select-change="selectTree"></Tree>
                            </div>
                        </Col>
                        <Col span="18">
                            <Operator :operator="operator" @clickOperator="clickOperator" @submit="submit"
                                      @reset="reset"/>
                        </Col>
                    </Row>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import IndicatorInfo from "./IndicatorInfo"
import Operator from "./Operator"
import GradeSelect from "./GradeSelect"
import {isRealNum} from "_p/basic/assets/contract/js/utils";
import {getGradeModelElementTreeNode, getVoByModelCodeAndElementNo, update} from "_p/afs-channel/api/grade-model"

import {getDictDataByType} from "_p/basic/api/admin/datadic";
import {deepClone} from '@/libs/utils/ObjectClone'

export default {
    // 配置评分要素
    name: 'GradeModelConfig',
    components: {IndicatorInfo, Operator, GradeSelect},
    props: {
        modalData: {
            type: Object,
            required: true
        },
        dataDict: {
            type: Object
        },
        modelCode: {
            type: String,
            required: true
        },
        modal: {
            type: Boolean,
            required: true
        },
    },
    data() {
        return {
            tableIndex: 0, //要素值 角标
            loading: false,
            operator: '', //计算翻译值
            formData: {
                highLimit: null,
                lowLimit: null
            },
            formValidate: {},
            gradeModelSelectDict: [],
            baseQueryData: [],
            tableHead: [],
            otherTable: [ //2-其他
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '评分模型指标计算公式',
                    key: 'score'
                },
            ],
            intervalTable: [ //1-区间型定值
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '要素值范围',
                    key: 'elementValueRange',
                    slot: 'elementValueRange'
                },
                {
                    title: '评分模型指标计算公式',
                    key: 'score'
                },
            ],
            dataDictTable: [ //0-数据字典定值
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '要素值',
                    key: 'elementValue',
                    slot: 'elementValue'
                },
                {
                    title: '评分模型指标计算公式',
                    key: 'score'
                },
            ],
            tableData: [],
            treeData: [],
        }
    },
    watch: {
        modal: function (newVal) {
            if (newVal) {
                this.init()
            }
        },
        formData: {
            handler(val, oldVal) {
                if (val && oldVal && val._index === oldVal._index) {
                    console.log(val, 'formData change', oldVal);
                    this.validateFormData(val)
                }
                // if(val && (typeof val.lowLimit === 'string' || val.lowLimit === undefined)){
                //     val.lowLimit = null
                // }
                // if(val && (typeof val.highLimit === 'string' || val.highLimit === undefined)){
                //     val.highLimit = null
                // }
            },
            deep: true
        }
    },
    mounted() {

    },
    methods: {
        init() {
            this.getTreeNode()
            this.gradeModelSelect()
        },
        // 评级指标树
        getTreeNode() {
            getGradeModelElementTreeNode(this.modelCode).then(res => {
                if (res.code === "0000" && res.data)
                    this.sortData(res.data)
            })
        },
        // 整理指标树
        sortData(data) {
            if (!Array.isArray(data) && data.length <= 0) return;
            // 一二级分类 特别注意 数据返回格式
            let firstLevel = data.filter(e => !e.pid),
                secondLevel = data.filter(e => e.pid),
                treeData = [];

            // console.log('firstLevel', firstLevel);
            // console.log('secondLevel', secondLevel);
            firstLevel.forEach(ele => {
                const {id, text} = ele;
                let title = this.getValue(text, this.dataDict.channelGradeLevel1ElementDict) || text
                let item = {id, title, children: [], expand: true}
                treeData.push(item)
            });
            secondLevel.forEach(ele => {
                const {id, text, pid} = ele;
                let title = this.getValue(text, this.dataDict.channelGradeElementDict) || text
                let item = {id, title, pid},
                    index = treeData.findIndex(e => e.id === pid);
                if (index >= 0) {
                    treeData[index].children.push(item)
                }
            })
            console.log(treeData, 'treeData')
            this.treeData = treeData;
            // this.loading = false;
        },
        // 要素值 table
        gradeModelSelect() {
            const {modelCode, elementNo, elementEditType, elementEditSrc} = this.modalData;
            this.loading = true
            if (elementEditType === "0") {
                this.tableHead = this.dataDictTable;
                getDictDataByType(elementEditSrc).then(res => {
                    if (res.code === "0000") {
                        this.gradeModelSelectDict = res.data;
                    }
                })
            } else if (elementEditType === "1") {
                this.tableHead = this.intervalTable;
            } else {
                this.tableHead = this.otherTable;
            }
            getVoByModelCodeAndElementNo(modelCode, elementNo).then(res => {
                this.loading = false
                if (res.code === "0000" && res.data) {
                    let d = deepClone(res.data)
                    if (d.length > 0) {
                        d.forEach(item => {
                            if(typeof item.lowLimit === 'string' || item.lowLimit === undefined){
                                item.lowLimit = null
                            }
                            if(typeof item.highLimit === 'string' || item.highLimit === undefined){
                                item.highLimit = null
                            }
                            item._index = this.tableIndex++
                        })
                        d[0]._highlight = true;
                        this.formData = d[0];
                        this.operator = d[0].score
                    }
                    this.tableData = d
                    this.baseQueryData = res.data
                }
            }).catch(e => {
                console.error(e);
                this.loading = false
            })
        },
        // 点击 表格
        onCurrentChange(row) {
            console.log(row);
            if (row) this.operator = row.score
            this.formData = row;
        },
        // 判断 formData 值是否正确
        validateFormData(formData) {
            const {highLimit, lowLimit, elementEditType} = formData;
            if (elementEditType === "1") {
                // if (isRealNum(highLimit) && isRealNum(lowLimit) && highLimit <= lowLimit) {
                    // this.$Message.warning('下限值不能大于或等于上限值，请重新输入！');
                    // return;
                // }
            }
            this.changeFormData(formData)
        },
        // formData  要素值 改变
        changeFormData(formData) {
            let data = deepClone(formData),
                d = [];

            this.tableData.forEach(ele => {
                if (data._index === ele._index) {
                    data._highlight = true;
                    d.push(data);
                } else {
                    ele._highlight = false;
                    d.push(ele)
                }
            })

            this.tableData = d
        },
        getRange(row) {
            if (!row) return;
            let range = '';
            const {highLimit, isHighLimit, isLowLimit, lowLimit} = row;
            range += isLowLimit ? '[' : '('
            range += typeof lowLimit === "number" ? (lowLimit + ',') : '-∞ ,'
            range += typeof highLimit === "number" ?  highLimit : '+∞'
            range += isHighLimit ? ']' : ')'
            // console.log(range);
            return range;
        },
        getValue(value, dict) {
            if (!value || !dict) return;
            for (let i = 0; i < dict.length; i++) {
                if (value === dict[i].value)
                    return dict[i].title
            }
            return '';
        },
        // 点击 树
        selectTree(list, item) {
            console.log(list, item);
            // this.operator += '[' + item.id + ']'
            if (item.pid) {
                this.operator += item.title
                this.formData.score += '[' + item.id + ']'
            }

        },
        // 点击 计算器
        clickOperator(val) {
            console.log(val);
            this.operator += this.transf(val)
            this.formData.score += val
        },
        // 点击 重置
        reset() {
            this.formData.score = '';
            this.operator = '';
        },
        // 点击 增加
        add() {
            console.log(this.modalData)
            const {elementName, elementNo, elementType, modelCode, elementEditType} = this.modalData

            let tableData = deepClone(this.tableData),
                obj = {
                    elementName, elementNo, elementType, modelCode, elementEditType,
                    highLimit: null,
                    isHighLimit: false,
                    isLowLimit: false,
                    lowLimit: null,
                    score: "",
                    _highlight: true,
                    _index: this.tableIndex++,
                    // lowLimitBack: 55,
                    // highLimitBack: 66,
                }

            tableData.forEach(ele => {
                ele._highlight = false;
            })
            tableData.push(obj)

            this.operator = ''
            this.formData = obj
            this.tableData = tableData
        },
        // 点击 删除
        del() {
            let data = deepClone(this.tableData),
                d = [],
                index = this.formData._index;
            data.forEach(ele => {
                if (ele._index !== index) {
                    ele._highlight = false;
                    d.push(ele)
                }
            })
            if (d[0]) {
                d[0]._highlight = true;
                this.formData = d[0]
                this.operator = d[0].score
            }

            this.tableData = d
        },
        // 操作符转换
        transf(title) {
            let val = title;
            switch (title) {
                case "X":
                    val = "实际值"
                    break;
                case "Y":
                    val = "权重值"
                    break;
                case "P":
                    val = "满意值"
                    break;
                case "S":
                    val = "不允许值"
                    break;
                case "R":
                    val = ".计算结果"
                    break;
            }
            return val;
        },
        getRes(str) { // str = score
            let substr = '{' + str.substring(str.length - 7, str.length - 1) + '}'

            return str.substring(0, str.length - 8) + substr;
        },
        // 点击 保存
        submit() {
            let base = this.baseQueryData,
                form = this.tableData,
                add = [],
                edit = [], del = [];
            form.forEach((item, index) => {
                if (!item.id) {
                    add.push(item)
                }
            })
            base.forEach((item, index) => {
                let fIndex = form.findIndex(e => e.id === item.id)
                if (fIndex >= 0) {
                    let {highLimit, isHighLimit, isLowLimit, lowLimit, score, elementValue} = form[fIndex];

                    if (item.elementValue !== elementValue || item.highLimit !== highLimit || item.isHighLimit !== isHighLimit || item.isLowLimit !== isLowLimit || item.lowLimit !== lowLimit || item.score !== score) {
                        edit.push(form[fIndex])
                    }
                } else {
                    del.push(item)
                }
            })

            update({insert: add, update: edit, delete: del}).then(res => {
                if (res.code === "0000") {
                    this.$Message.success(res.data)
                    this.$emit('closeModal', true)
                }
            })
        }
    },
}
</script>

<style lang="less">
.operator-btns {
    display: flex;
    flex-flow: column nowrap;

    > div {
        padding: 4px 0;
    }
}

.table-btn {
    padding-bottom: 16px;
}

.grade-model-tree {
    width: 100%;
    max-height: 500px;
    overflow: auto;
}
</style>
